<template>
  <div class="angle-measurement">
    <div class="page-header">
      <h2>角度测量</h2>
      <p>测量骨骼的解剖或力学轴角度</p>
    </div>

    <div class="content-wrapper">
      <!-- 左侧测量工具 -->
      <div class="measurement-panel">
        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>测量工具</span>
            </div>
          </template>

          <div class="measurement-tools">
            <el-button-group class="tool-group">
              <el-button
                :type="currentTool === 'anatomical' ? 'primary' : ''"
                @click="selectTool('anatomical')"
              >
                <el-icon><Compass /></el-icon>
                解剖轴
              </el-button>
              <el-button
                :type="currentTool === 'mechanical' ? 'primary' : ''"
                @click="selectTool('mechanical')"
              >
                <el-icon><Operation /></el-icon>
                力学轴
              </el-button>
            </el-button-group>

            <div class="angle-types">
              <h4>常用角度测量</h4>
              <div class="angle-buttons">
                <el-button size="small" @click="measureAngle('mpta')">MPTA</el-button>
                <el-button size="small" @click="measureAngle('ldfa')">LDFA</el-button>
                <el-button size="small" @click="measureAngle('mptfa')">MPTFA</el-button>
                <el-button size="small" @click="measureAngle('adfa')">ADFA</el-button>
                <el-button size="small" @click="measureAngle('hka')">HKA</el-button>
                <el-button size="small" @click="measureAngle('fta')">FTA</el-button>
              </div>
            </div>

            <div class="custom-measurement">
              <h4>自定义测量</h4>
              <el-button type="dashed" block @click="startCustomMeasurement">
                <el-icon><Plus /></el-icon>
                新建角度测量
              </el-button>
            </div>
          </div>
        </el-card>

        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>测量结果</span>
            </div>
          </template>

          <div class="measurement-results">
            <div v-if="measurements.length === 0" class="empty-results">
              <el-icon><DataAnalysis /></el-icon>
              <p>暂无测量数据</p>
            </div>

            <div v-else class="results-list">
              <div
                v-for="(measurement, index) in measurements"
                :key="index"
                class="result-item"
                :class="{ active: selectedMeasurement === index }"
                @click="selectMeasurement(index)"
              >
                <div class="result-header">
                  <span class="result-name">{{ measurement.name }}</span>
                  <el-button
                    type="text"
                    size="small"
                    @click.stop="deleteMeasurement(index)"
                  >
                    <el-icon><Delete /></el-icon>
                  </el-button>
                </div>
                <div class="result-value">{{ measurement.value }}°</div>
                <div class="result-type">{{ measurement.type }}</div>
              </div>
            </div>

            <div v-if="measurements.length > 0" class="results-summary">
              <el-divider />
              <div class="summary-item">
                <span>总计测量: {{ measurements.length }} 项</span>
              </div>
              <div class="summary-actions">
                <el-button size="small" @click="exportResults">
                  <el-icon><Download /></el-icon>
                  导出结果
                </el-button>
                <el-button size="small" @click="clearAllResults">
                  <el-icon><Delete /></el-icon>
                  清空
                </el-button>
              </div>
            </div>
          </div>
        </el-card>

        <el-card class="tool-card">
          <template #header>
            <div class="card-header">
              <span>参考值</span>
            </div>
          </template>

          <div class="reference-values">
            <div class="reference-item">
              <label>MPTA (正常值)</label>
              <span>87° ± 5°</span>
            </div>
            <div class="reference-item">
              <label>LDFA (正常值)</label>
              <span>81° ± 2°</span>
            </div>
            <div class="reference-item">
              <label>HKA (正常值)</label>
              <span>1.3° ± 2°</span>
            </div>
            <div class="reference-item">
              <label>FTA (正常值)</label>
              <span>6° ± 2°</span>
            </div>
          </div>
        </el-card>
      </div>

      <!-- 右侧画布区域 -->
      <div class="canvas-area">
        <el-card class="canvas-card">
          <template #header>
            <div class="canvas-header">
              <span>角度测量画布</span>
              <div class="canvas-controls">
                <el-button-group size="small">
                  <el-button @click="zoomIn">
                    <el-icon><ZoomIn /></el-icon>
                  </el-button>
                  <el-button @click="zoomOut">
                    <el-icon><ZoomOut /></el-icon>
                  </el-button>
                  <el-button @click="resetZoom">
                    <el-icon><Refresh /></el-icon>
                  </el-button>
                </el-button-group>

                <el-button-group size="small">
                  <el-button @click="toggleGrid">
                    <el-icon><Menu /></el-icon>
                    {{ showGrid ? '隐藏' : '显示' }}网格
                  </el-button>
                  <el-button @click="toggleMeasurements">
                    <el-icon><View /></el-icon>
                    {{ showMeasurements ? '隐藏' : '显示' }}测量
                  </el-button>
                </el-button-group>
              </div>
            </div>
          </template>

          <div class="canvas-container" ref="canvasContainer">
            <canvas
              ref="measurementCanvas"
              class="measurement-canvas"
              @mousedown="startMeasuring"
              @mousemove="updateMeasuring"
              @mouseup="completeMeasuring"
              @contextmenu.prevent="showContextMenu"
            ></canvas>

            <div v-if="!imageLoaded" class="canvas-placeholder">
              <el-icon class="placeholder-icon"><Picture /></el-icon>
              <p>请先在影像分析模块加载X光图像</p>
              <el-button type="primary" @click="goToImageAnalysis">
                <el-icon><Right /></el-icon>
                前往影像分析
              </el-button>
            </div>

            <!-- 测量状态提示 -->
            <div v-if="measuring" class="measuring-tip">
              <div class="tip-content">
                <el-icon><Aim /></el-icon>
                <span>{{ getMeasuringTip() }}</span>
              </div>
            </div>
          </div>

          <div class="canvas-status">
            <span>坐标: ({{ mouseX }}, {{ mouseY }})</span>
            <span>缩放: {{ Math.round(zoomLevel) }}%</span>
            <span v-if="currentMeasurement">当前角度: {{ currentMeasurement }}°</span>
          </div>
        </el-card>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue'
import { useStore } from '../../store'
import {
  Compass,
  Operation,
  Plus,
  DataAnalysis,
  Delete,
  Download,
  ZoomIn,
  ZoomOut,
  Refresh,
  Menu,
  View,
  Picture,
  Right,
  Aim
} from '@element-plus/icons-vue'

// 全局状态
const store = useStore()

// 响应式数据
const currentTool = ref('anatomical')
const measurements = ref([])
const selectedMeasurement = ref(-1)
const measuring = ref(false)
const mouseX = ref(0)
const mouseY = ref(0)
const zoomLevel = ref(100)
const showGrid = ref(true)
const showMeasurements = ref(true)
const currentMeasurement = ref(null)

// 计算属性 - 检查全局图像状态
const imageLoaded = computed(() => store.getters.isImageLoaded())

// 测量状态
const measurementState = ref({
  step: 0, // 0: 未开始, 1: 第一个点, 2: 第二个点, 3: 第三个点
  points: [],
  type: '',
  name: ''
})

// DOM引用
const canvasContainer = ref(null)
const measurementCanvas = ref(null)

// 工具选择
const selectTool = (tool) => {
  currentTool.value = tool
  resetMeasurement()
}

// 角度测量
const measureAngle = (angleType) => {
  const angleNames = {
    mpta: '胫骨内侧平台角',
    ldfa: '股骨外侧远端角',
    mptfa: '胫骨内侧后倾角',
    adfa: '股骨前弓角',
    hka: '髋膝踝角',
    fta: '股胫角'
  }

  startAngleMeasurement(angleType, angleNames[angleType])
}

const startAngleMeasurement = (type, name) => {
  resetMeasurement()
  measurementState.value = {
    step: 0,
    points: [],
    type: type,
    name: name
  }
  measuring.value = true
}

const startCustomMeasurement = () => {
  ElMessageBox.prompt('请输入测量名称', '自定义角度测量', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputPattern: /\S+/,
    inputErrorMessage: '请输入有效的测量名称'
  }).then(({ value }) => {
    startAngleMeasurement('custom', value)
  }).catch(() => {
    // 用户取消
  })
}

const resetMeasurement = () => {
  measuring.value = false
  measurementState.value = {
    step: 0,
    points: [],
    type: '',
    name: ''
  }
  currentMeasurement.value = null
}

// 画布事件
const startMeasuring = (event) => {
  if (!measuring.value) return

  const rect = measurementCanvas.value.getBoundingClientRect()
  const x = event.clientX - rect.left
  const y = event.clientY - rect.top

  measurementState.value.points.push({ x, y })
  measurementState.value.step++

  if (measurementState.value.step === 3) {
    // 完成三点角度测量
    const angle = calculateAngle(measurementState.value.points)
    addMeasurementResult(measurementState.value.name, angle, measurementState.value.type)
    resetMeasurement()
  }
}

const updateMeasuring = (event) => {
  const rect = measurementCanvas.value.getBoundingClientRect()
  mouseX.value = Math.round(event.clientX - rect.left)
  mouseY.value = Math.round(event.clientY - rect.top)

  if (measuring.value && measurementState.value.step === 2) {
    // 实时显示当前角度
    const tempPoints = [...measurementState.value.points, { x: mouseX.value, y: mouseY.value }]
    currentMeasurement.value = calculateAngle(tempPoints).toFixed(1)
  }
}

const completeMeasuring = (event) => {
  // 在startMeasuring中处理
}

const showContextMenu = (event) => {
  // 右键菜单功能
  console.log('显示右键菜单')
}

// 计算角度
const calculateAngle = (points) => {
  if (points.length !== 3) return 0

  const [p1, p2, p3] = points

  // 计算向量
  const v1 = { x: p1.x - p2.x, y: p1.y - p2.y }
  const v2 = { x: p3.x - p2.x, y: p3.y - p2.y }

  // 计算角度
  const dot = v1.x * v2.x + v1.y * v2.y
  const mag1 = Math.sqrt(v1.x * v1.x + v1.y * v1.y)
  const mag2 = Math.sqrt(v2.x * v2.x + v2.y * v2.y)

  const angle = Math.acos(dot / (mag1 * mag2)) * (180 / Math.PI)
  return Math.round(angle * 10) / 10
}

// 测量结果管理
const addMeasurementResult = (name, value, type) => {
  measurements.value.push({
    name,
    value,
    type,
    timestamp: new Date().toLocaleString()
  })
}

const selectMeasurement = (index) => {
  selectedMeasurement.value = index
}

const deleteMeasurement = (index) => {
  measurements.value.splice(index, 1)
  if (selectedMeasurement.value === index) {
    selectedMeasurement.value = -1
  }
}

const exportResults = () => {
  console.log('导出测量结果')
  // 实现导出功能
}

const clearAllResults = () => {
  ElMessageBox.confirm('确定要清空所有测量结果吗？', '确认清空', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    measurements.value = []
    selectedMeasurement.value = -1
  }).catch(() => {
    // 用户取消
  })
}

// 画布控制
const zoomIn = () => {
  zoomLevel.value = Math.min(500, zoomLevel.value + 25)
}

const zoomOut = () => {
  zoomLevel.value = Math.max(25, zoomLevel.value - 25)
}

const resetZoom = () => {
  zoomLevel.value = 100
}

const toggleGrid = () => {
  showGrid.value = !showGrid.value
}

const toggleMeasurements = () => {
  showMeasurements.value = !showMeasurements.value
}

const goToImageAnalysis = () => {
  console.log('跳转到影像分析模块')
}

const getMeasuringTip = () => {
  const tips = {
    0: '请点击第一个测量点',
    1: '请点击第二个测量点（角度顶点）',
    2: '请点击第三个测量点完成角度测量'
  }
  return tips[measurementState.value.step] || '测量中...'
}

onMounted(() => {
  nextTick(() => {
    if (measurementCanvas.value) {
      const canvas = measurementCanvas.value
      canvas.width = 800
      canvas.height = 600

      // 绘制示例内容
      const ctx = canvas.getContext('2d')
      ctx.fillStyle = '#f8f9fa'
      ctx.fillRect(0, 0, canvas.width, canvas.height)

      if (showGrid.value) {
        drawGrid(ctx, canvas.width, canvas.height)
      }
    }
  })
})

const drawGrid = (ctx, width, height) => {
  ctx.strokeStyle = '#e8e8e8'
  ctx.lineWidth = 1

  const gridSize = 20

  for (let i = 0; i <= width; i += gridSize) {
    ctx.beginPath()
    ctx.moveTo(i, 0)
    ctx.lineTo(i, height)
    ctx.stroke()
  }

  for (let i = 0; i <= height; i += gridSize) {
    ctx.beginPath()
    ctx.moveTo(0, i)
    ctx.lineTo(width, i)
    ctx.stroke()
  }
}
</script>

<style scoped>
/* 使用与ImageAnalysis类似的样式结构 */
.angle-measurement {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.page-header {
  margin-bottom: 24px;
}

.page-header h2 {
  margin: 0 0 8px 0;
  color: #262626;
  font-size: 24px;
  font-weight: 500;
}

.page-header p {
  margin: 0;
  color: #8c8c8c;
  font-size: 14px;
}

.content-wrapper {
  flex: 1;
  display: flex;
  gap: 24px;
  min-height: 0;
}

.measurement-panel {
  width: 320px;
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.tool-card {
  flex-shrink: 0;
}

.card-header {
  font-weight: 500;
  color: #262626;
}

.measurement-tools {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.tool-group {
  width: 100%;
}

.tool-group .el-button {
  flex: 1;
}

.angle-types h4,
.custom-measurement h4 {
  margin: 0 0 12px 0;
  font-size: 14px;
  color: #595959;
  font-weight: 500;
}

.angle-buttons {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 8px;
}

.measurement-results {
  max-height: 300px;
  overflow-y: auto;
}

.empty-results {
  text-align: center;
  padding: 40px 0;
  color: #8c8c8c;
}

.empty-results .el-icon {
  font-size: 32px;
  margin-bottom: 12px;
}

.results-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.result-item {
  padding: 12px;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-item:hover {
  border-color: #1890ff;
  background-color: #f0f9ff;
}

.result-item.active {
  border-color: #1890ff;
  background-color: #e6f7ff;
}

.result-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 4px;
}

.result-name {
  font-weight: 500;
  color: #262626;
}

.result-value {
  font-size: 18px;
  font-weight: 600;
  color: #1890ff;
  margin-bottom: 4px;
}

.result-type {
  font-size: 12px;
  color: #8c8c8c;
}

.results-summary {
  margin-top: 16px;
}

.summary-item {
  margin-bottom: 12px;
  font-size: 14px;
  color: #595959;
}

.summary-actions {
  display: flex;
  gap: 8px;
}

.reference-values {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.reference-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
}

.reference-item label {
  font-size: 14px;
  color: #595959;
}

.reference-item span {
  font-weight: 500;
  color: #262626;
}

.canvas-area {
  flex: 1;
  min-width: 0;
}

.canvas-card {
  height: 100%;
  display: flex;
  flex-direction: column;
}

.canvas-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  width: 100%;
}

.canvas-controls {
  display: flex;
  gap: 12px;
}

.canvas-container {
  flex: 1;
  position: relative;
  background: #f8f9fa;
  border: 1px solid #e8e8e8;
  border-radius: 6px;
  overflow: hidden;
  min-height: 400px;
}

.measurement-canvas {
  width: 100%;
  height: 100%;
  cursor: crosshair;
}

.canvas-placeholder {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
  color: #8c8c8c;
}

.placeholder-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.measuring-tip {
  position: absolute;
  top: 20px;
  left: 50%;
  transform: translateX(-50%);
  background: rgba(0, 0, 0, 0.8);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 14px;
  z-index: 10;
}

.tip-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

.canvas-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 0;
  font-size: 12px;
  color: #8c8c8c;
  border-top: 1px solid #f0f0f0;
}

:deep(.el-card__body) {
  padding: 16px;
}
</style>
